﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Il2CppAnti
{
    class BlockIl2cppMetadata : IBlock
    {
        public string Name => "il2cpp-metadata";

        public string Target => Paths.METADATA_HEADER;

        public Paths Paths { get; set; }

        public bool Diff { get; set; }

        public BlockIl2cppMetadata(Paths paths)
        {
            Paths = paths;
        }

        public void Backup()
        {
            if (!File.Exists(Target + ".bak"))
                File.Copy(Target, Target + ".bak");
        }

        public bool Exists()
        {
            return File.Exists(Path.Combine(Paths.BLOCK_ROOT, Name));
        }

        public string Read()
        {
            return File.ReadAllText(Target);
        }

        public void Write()
        {
            var c = Read();
            var o = OldBlock();
            var n = NewBlock();
            c = c.Replace(o, n);
            File.WriteAllText(Target, c);
            Console.WriteLine($"{Target} 修改成功 .");
        }

        public string NewBlock()
        {
            return File.ReadAllText(Path.Combine(Paths.BLOCK_ROOT, Name + ".new")).Replace("\r", "");
        }

        public string OldBlock()
        {
            return File.ReadAllText(Path.Combine(Paths.BLOCK_ROOT, Name)).Replace("\r", "");
        }

        public bool Replace()
        {
            var c = Read();
            var b = NewBlock();
            if (c.Contains(b))
                return (Diff = false);
            Backup();
            Write();
            return (Diff = true);
        }

        public void Decompile()
        {
        }

        public void Compile()
        {
        }
    }
}
